#include "mainwindowimpl.h"
#include "serie.h"
#include <QtNetwork/QUrlInfo>
//
MainWindowImpl::MainWindowImpl( QWidget * parent, Qt::WFlags f) 
	: QMainWindow(parent, f)
{
	setupUi(this);

        //manejador de http get
        //http = new HttpEngine();
        //connect(http->timerWeb, SIGNAL(timeout()), this, SLOT(updateWeb()));

        // inserta plot en el frame
        //const double intervalLength = 60.0 - QTime::currentTime().second(); // seconds
        plot = new Plot(plotFrame);
        //plot->setIntervalLength(plot->getIntervalLength());
        QHBoxLayout *layout = new QHBoxLayout(plotFrame);
        layout->addWidget(plot,10);
        tSetSpinBox->setValue(plot->getTSet());
        tRangeSpinBox->setValue(plot->getTRange());
        //------------------------------------------------

        //Configura puerto a conetar y comboBox
        if(configHandler.existPortOptions()){
            QList<QString> portDeviceList;

            portDeviceList = configHandler.getPortDevice();
            if(!portDeviceList.isEmpty()){
                for(int i=0; i < portDeviceList.size(); i++){
                    portDeviceComboBox->addItem(portDeviceList.at(i));
                }
            }

            if(configHandler.existPortConfig()){
                QPair<QString, QString> portSetting = configHandler.getPortConfig();
                portDeviceComboBox->setCurrentIndex(portDeviceComboBox->findText(portSetting.first));

                //qport->setPort(portDeviceComboBox->currentText());
            }
        }
        //------------------------------------------------

        //pone color de fondo a los labels
        // conectado/desconectado
        QPalette p = connectionLabel->palette();
        p.setColor(connectionLabel->backgroundRole(), QColor(Qt::red));
        connectionLabel->setPalette(p);
        connectionLabel->setAutoFillBackground(true);
        connectionLabel->update();
        // aire
        p = aireLabel->palette();
        p.setColor(aireLabel->backgroundRole(), QColor(Qt::gray));
        aireLabel->setPalette(p);
        aireLabel->setAutoFillBackground(true);
        aireLabel->update();

        // todos los connect
//        connect(qport,SIGNAL(newData(QByteArray)),this,SLOT(receivedSerial(QByteArray)));
//        connect(connectButton, SIGNAL(toggled(bool)), this, SLOT(connectionStateSet(bool)));
//        connect(readConfigurationButton, SIGNAL(clicked()), this, SLOT(readConfiguration()));
//        connect(writeConfigurationButton, SIGNAL(clicked()), this, SLOT(writeConfiguration()));
//        connect(this, SIGNAL(temperatureReceived(double)), this, SLOT(refreshLCDTemperature(double)));
//        connect(this, SIGNAL(temperatureReceived(double)), this, SLOT(addTemperatureToPlot(double)));
//        connect(this, SIGNAL(textToLog(QString)), this, SLOT(logAppend(QString)));
//        connect(tSetSpinBox, SIGNAL(valueChanged(double)), plot, SLOT(setTSet(double)));
//        connect(tRangeSpinBox, SIGNAL(valueChanged(double)), plot, SLOT(setTRange(double)));
//        connect(this, SIGNAL(configurationReceived(double,double)), this, SLOT(configurationTemperatureReceived(double,double)));
//        connect(this, SIGNAL(aireStateReceived(int)), this, SLOT(aireStateChange(int)));
//        connect(this, SIGNAL(getConfiguration()), this, SLOT(readConfiguration()));
//        connect(this, SIGNAL(setConfiguration()), this, SLOT(writeConfiguration()));

        //connect(http->nam, SIGNAL(finished(QNetworkReply*)), http->nam, SLOT(finishedSlot(QNetworkReply*)));

        //LO DE QEXTSERIALPORT
        // creamos un timer que se encargará de mirar el puerto serie
            timer = new QTimer();

            // activar/desactivar los botones que toque
            btPuertoAbrir->setEnabled(true);
            btPuertoCerrar->setEnabled(false);

            // hacer las conexiones
            connect(btPuertoAbrir,SIGNAL(clicked()),this,SLOT(btPuertoAbrir_pulsado()));
            connect(btPuertoCerrar,SIGNAL(clicked()),this,SLOT(btPuertoCerrar_pulsado()));

            connect(timer, SIGNAL(timeout()), this, SLOT(timer_Tick()));

}

MainWindowImpl::~MainWindowImpl(){
    delete plot;
}


void MainWindowImpl::parseLineReceived(QString dataToParse){
    //parseo de la informacion que esta enviando
    bool ok;
    double tSetReceived, tRangeReceived;
    int function = dataToParse.left(2).toInt(&ok,10);

    emit textToLog(dataToParse);

    switch(function){
    case 1: //recibo temperatura sensada
        dataToParse.replace(0,22,"");
        emit temperatureReceived(dataToParse.toDouble(&ok));
        break;
    case 2: //recibo tset y trange
        dataToParse.remove("02-Tset:");
        tSetReceived = dataToParse.left(5).toDouble(&ok);
        dataToParse.replace(0, 13, "");
        tRangeReceived = dataToParse.left(4).toDouble(&ok);
        emit configurationReceived(tSetReceived,tRangeReceived);
        break;
    case 3:
        dataToParse.remove("03-Aire_state:");
        emit aireStateReceived(dataToParse.left(1).toInt(&ok,10));
        break;
    case 4: //recibo alarm state
        dataToParse.remove("04-Alarm_state:");
        //emit alarmStateReceived(dataToParse.left(1).toInt(&ok,10));
        break;
    //recepcion de ACK
    case 10:
        dataToParse.remove("10-");
        emit textToLog(dataToParse);
        emit textToLog(">>> conexion exitosa!!!");
        //emit getConfiguration();
        break;
    case 11:
        emit textToLog(">>> PARAMETROS DE CONFIGURACION SETEADOS CORRECTAMENTE");
        break;
    case 21:
        emit textToLog(">>> PARAMETROS DE CONFIGURACION RECIBIDOS DESDE DISPOSITIVO");
        break;
    default: break;
    }

}


// ------------------- SLOTS --------------------------------
void MainWindowImpl::receivedSerial(QByteArray dato){
    QList<QByteArray> dataSplit = dato.split('\r');
    dataReceived.append(dataSplit.first());
    if(dataSplit.count()>1){
        dataReceived.remove("\r");
        //logTextBrowser->append(dataReceived);
        parseLineReceived(dataReceived);
        dataReceived.clear();
        dataSplit.removeFirst();
        dataReceived.append(dataSplit.first());
    }

}

void MainWindowImpl::connectionStateSet(bool state){
    QPalette p = connectionLabel->palette();
    if(true){//qport->isOpen()){
        //CONECTADO!!!
        QByteArray dato = "00-Establecer_conexion\r";
        //qport->sendData(dato);
        emit textToLog("<<< CONECTANDO...");
        connectionLabel->setText("CONECTADO");
        connectButton->setText("DESCONECTAR");
        emit getConfiguration(); //hay q borrarlo una vez cambie el soft del pic y descomentar el otro!!!
        plot->start();
        readConfigurationButton->setEnabled(true);
        writeConfigurationButton->setEnabled(true);
        //pone color de fondo del layer de conexion a rojo
        p.setColor(connectionLabel->backgroundRole(),QColor(Qt::green));
        //http->start();
    }else{
        connectionLabel->setText("DESCONECTADO");
        connectButton->setText("CONECTAR");
        plot->stop();
        readConfigurationButton->setEnabled(false);
        writeConfigurationButton->setEnabled(false);
        //pone color de fondo del layer de conexion a rojo
        p.setColor(connectionLabel->backgroundRole(), QColor(Qt::red));

    }
    connectionLabel->setPalette(p);
    connectionLabel->setAutoFillBackground(true);
    connectionLabel->update();
}

void MainWindowImpl::readConfiguration(){
    QByteArray dato = "20-LeerParametros\r";
    //qport->sendData(dato);
    emit textToLog("<<< PARAMETROS DE CONFIGURACION SOLICITADOS");
}

void MainWindowImpl::writeConfiguration(){
    QByteArray paramSend;
    QString st= QString("10-%1-%2\r").arg(tSetSpinBox->value()).arg(tRangeSpinBox->value());
    paramSend.append(st);
    //qport->sendData(paramSend);
}

void MainWindowImpl::refreshLCDTemperature(double value){
    actualTemperatureLCD->display(value);
    QPalette p(actualTemperatureLCD->palette());
    if(value > plot->getTSet() + plot->getTRange()){
        //pone letra a rojo
        p.setColor(QPalette::WindowText,Qt::red);
    }else{
        //pone letra en negro
        p.setColor(QPalette::WindowText,Qt::black);
    }
    actualTemperatureLCD->setPalette(p);
}

void MainWindowImpl::addTemperatureToPlot(double value){
    //manda temperatura al grafo
    const QPointF s(plot->getTimeFromMidnight(), value);
    SignalData::instance().append(s);
}

void MainWindowImpl::logAppend(QString txt){
    QString textToLog = QDate::currentDate().toString("dd/MM/yyyy - ");
    textToLog.append(QTime::currentTime().toString("HH:mm:ss - "));
    textToLog.append(txt);
    logTextBrowser->append(textToLog);
}

void MainWindowImpl::aireStateChange(int state){
    QPalette p(aireLabel->palette());
    if(state == 0){
        aireLabel->setText("AIRE APAGADO");
        //pone color de fondo del layer a gris
        p.setColor(aireLabel->backgroundRole(), QColor(Qt::gray));
    }else{
        aireLabel->setText("AIRE ENCENDIDO");
        //pone color de fondo del layer a verde
        p.setColor(aireLabel->backgroundRole(), QColor(Qt::green));
    }
    aireLabel->setPalette(p);
    aireLabel->setAutoFillBackground(true);
    aireLabel->update();
}

void MainWindowImpl::configurationTemperatureReceived(double tSetReceived, double tRangeReceived){
    tSetSpinBox->setValue(tSetReceived);
    tRangeSpinBox->setValue(tRangeReceived);
}

void MainWindowImpl::updateWeb(){
    //http->sendTemperatureToWeb(actualTemperatureLCD->value(), 0);
}

//------------------------------------------------------------------------------


//-- no lo usamos -------------------------------------------------------------
void MainWindowImpl::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        retranslateUi(this);
        break;
    default:
        break;
    }
}

//-- slot para el boton de Abrir puerto ---------------------------------------
void MainWindowImpl::btPuertoAbrir_pulsado(void) {
    if (serie_openConnection("/dev/ttyS1") == false) {   // fallo
           // sacar un mensaje
        // QMessageBox::information(this, tr("Cuidadínnn!!!!"), tr("No se ha podido abrir el puerto\nQuizá probando otro ..."));
        //lePuertoNombre->setText(tr("NO EXISTE"));
        qDebug() << "EL PUERTO NO EXISTE";
    } else {
        btPuertoAbrir->setEnabled(false);
        btPuertoCerrar->setEnabled(true);

        qDebug() << "Puerto abierto!!!";
        timer->start(500);  // un tick cada 500 mS
    }
}

//-- slot para el boton de cerrar puerto --------------------------------------
void MainWindowImpl::btPuertoCerrar_pulsado(void) {

    timer->stop();

    // activar/desactivar los botones que toque
    btPuertoAbrir->setEnabled(true);
    btPuertoCerrar->setEnabled(false);

    serie_closeConnection();
}

//-- slot para el boton de enviar texto ---------------------------------------
// se pretende enviar por el serie lo que en la linea de edición
void MainWindowImpl::btPuertoEnviarTexto_pulsado(void){
    //serie_sendStr(leTextoEnviar->text().toAscii().data());
}

//-- slot para el timer -------------------------------------------------------
// se usa para comprobar si ha llegado algo por el serie
void MainWindowImpl::timer_Tick(void) {

    char tmp_buff[1000]; // buffer de recepción
    int num_bytes;

    num_bytes = serie_receiveData(tmp_buff, 999);
    if (num_bytes > 0) {
          tmp_buff[num_bytes] = '\0';
          //leRecibido->setText(tmp_buff);
          printf("Rebuts %d bytes\n", num_bytes);
          qDebug() << num_bytes;
    }
}
